package xuecheng.tool.json.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.google.gson.*;

import cn.hutool.core.date.DatePattern;
import lombok.Getter;
import xuecheng.tool.json.JsonUtils;

/**
 * gson 实现
 *
 * @author PengXueCheng
 * @version 1.0.0
 */
public class JsonUtilsGsonImpl implements JsonUtils {

    private static final JsonUtilsGsonImpl INSTANCE = new JsonUtilsGsonImpl();
    @Getter
    private final Gson GSON =
        new GsonBuilder().disableHtmlEscaping().setDateFormat(DatePattern.PURE_DATETIME_MS_PATTERN).create();

    private JsonUtilsGsonImpl() {}

    public static JsonUtilsGsonImpl getInstance() {
        return INSTANCE;
    }

    @Override
    public String toJson(Object src) {
        return GSON.toJson(src);
    }

    @Override
    public <T> T fromJsonAsObject(String json, Class<T> classOfT) {
        return GSON.fromJson(json, classOfT);
    }

    @Override
    public <T> List<T> fromJsonAsArray(String json, Class<T> classOfT) {
        JsonElement jsonElement = JsonParser.parseString(json);
        JsonArray jsonArray = jsonElement.getAsJsonArray();
        List<T> list = new ArrayList<>();
        for (JsonElement element : jsonArray) {
            T t = GSON.fromJson(element, classOfT);
            list.add(t);
        }
        return list;
    }

    @Override
    public String getAsString(String json, String memberName) {
        JsonElement jsonElement = getJsonElement(json, memberName);
        return GSON.fromJson(jsonElement, String.class);
    }

    private JsonElement getJsonElement(String json, String memberName) {
        JsonObject jsonObject = JsonParser.parseString(json).getAsJsonObject();
        return jsonObject.get(memberName);
    }

    @Override
    public int getAsInt(String json, String memberName) {
        JsonElement jsonElement = getJsonElement(json, memberName);
        return GSON.fromJson(jsonElement, int.class);
    }

    @Override
    public Date getAsDate(String json, String memberName) {
        JsonElement jsonElement = getJsonElement(json, memberName);
        return GSON.fromJson(jsonElement, Date.class);
    }

    @Override
    public boolean getAsBoolean(String json, String memberName) {
        JsonElement jsonElement = getJsonElement(json, memberName);
        return GSON.fromJson(jsonElement, boolean.class);
    }

    @Override
    public <T> T getAsObj(String json, String memberName, Class<T> classOfT) {
        JsonElement jsonElement = getJsonElement(json, memberName);
        return GSON.fromJson(jsonElement, classOfT);
    }

}
